<template>
  <div>
    <el-card>
      <div class="select_box">
        <el-row>
          <el-col :span="7">
            <div class="title">工程名称</div>
            <el-input style="width:80%" v-model="selectInfo.name" size="small" placeholder="请输入"></el-input>
          </el-col>
          <el-col :span="7">
            <div class="title">工程编号</div>
            <el-input style="width:80%" v-model="selectInfo.number" size="small" placeholder="请输入"></el-input>
          </el-col>
          <!-- <el-col :span="7">
            <div class="title">勘察单号</div>
            <el-input style="width:80%" v-model="selectInfo.surveyNumber" size="small" placeholder="请输入"></el-input>
          </el-col> -->
          <el-col :span="7">
            <div class="title">地点</div>
            <el-input style="width:80%" v-model="selectInfo.location" size="small" placeholder="请输入"></el-input>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px;">
          <!-- <el-col :span="7">
            <div class="title">施工时间</div>
            <el-date-picker
              style="width:80%"
              v-model="selectInfo.date"
              size="small"
              type="daterange"
              format="yyyy-MM-dd"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-col> -->
          <el-col :span="7">
            <div class="title">状态</div>
            <el-select style="width:80%" v-model="selectInfo.auditStatus" size="small" clearable placeholder="请选择">
              <el-option 
                v-for="item in schemeAuditStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px;">
          <el-col :span="12">
            <el-button size="small" @click="reset">重置</el-button>
						<el-button type="primary" size="small" @click="handleChangePage">确定</el-button>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-button size="small" @click="exportList">导出施工方案</el-button>
						<el-button type="primary" size="small" @click="ticketDetail={}, showSelect=true">新建施工方案</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="table_box">
        <el-table ref="multipleTable" :data="tableData" v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="45">
          </el-table-column>
					<el-table-column prop="name" label="名称">
					</el-table-column>
          <el-table-column prop="number" label="工程编号">
            <template slot-scope="scope">
              <span style="color: #409EFF;cursor: pointer;" @click="surveyId=scope.row.surveyId, showSurveyDetail=true">{{ scope.row.number }}</span>
						</template>
          </el-table-column>
					<!-- <el-table-column prop="surveyNumber" label="勘察单号">
            <template slot-scope="scope">
              <span style="color: #409EFF;cursor: pointer;" @click="surveyId=scope.row.surveyId, showSurveyDetail=true">{{ scope.row.surveyNumber }}</span>
						</template>
					</el-table-column> -->
					<el-table-column prop="location" label="地点">
					</el-table-column>
					<!-- <el-table-column prop="date" label="施工时间">
            <template slot-scope="scope">
							{{ scope.row.startDate && scope.row.endDate ? dateFormat(scope.row.startDate) + ' 至 ' +  dateFormat(scope.row.endDate) : '-' }}
						</template>
					</el-table-column> -->
          <el-table-column prop="safetyManager" label="提交审批时间" v-if="type!='list'">submitTime
            <template slot-scope="scope">
							{{ scope.row.submitTime  ? dateFormat(scope.row.submitTime) : '-' }}
						</template>
					</el-table-column>
          <!-- <el-table-column prop="safetyManager" label="安全负责人">
					</el-table-column> -->
          <el-table-column prop="auditStatus" label="状态" width="120">
            <template slot-scope="scope">
							{{ scope.row.auditStatus < 4 ? schemeAuditStatus[scope.row.auditStatus].label : '-' }}
						</template>
					</el-table-column>
					<el-table-column fixed="right" label="操作" width="180" v-if="type==='list'">
						<template slot-scope="scope">
							<el-button @click="detailId=scope.row.id, showDetail=true" type="text" size="small">详情</el-button>
              <el-button size="small" type="text" @click="ticketDetail=scope.row, showSelect=true" :disabled="scope.row.auditStatus===1 || scope.row.auditStatus === 2">编辑</el-button>
						</template>
					</el-table-column>
          <el-table-column fixed="right" label="操作" width="200" v-else>
						<template slot-scope="scope">
							<el-button type="text" @click="detailId=scope.row.id, showDetail=true" size="small">查看详情</el-button>
              <div style="display: inline-block;">
                <el-popconfirm
                  style="margin-left: 10px;"
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  icon-color="#67c23a"
                  title="是否通过该审核？"
                  @confirm="process(scope.row, 2)">
                  <el-button size="small" type="text" :disabled="scope.row.auditStatus!=1" slot="reference">通过</el-button>
                </el-popconfirm>
                <el-popconfirm
                  style="margin-left: 10px;"
                  confirm-button-text='确定'
                  cancel-button-text='取消'
                  icon="el-icon-info"
                  icon-color="red"
                  title="是否驳回该审核？"
                  @confirm="process(scope.row, 3)">
                  <el-button size="small" type="text" :disabled="scope.row.auditStatus!=1" :style="scope.row.auditStatus!=1 ? 'color: #C0C4CC;' : 'color: red;'" slot="reference">驳回</el-button>
                </el-popconfirm>
              </div>
						</template>
					</el-table-column>
				</el-table>
        <div class="footer">
          <el-pagination @current-change="handleChangePage" :current-page.sync="pageNum" :page-size="pageSize" layout="prev, pager, next" :total="total"></el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 创建/编辑施工票页面 -->
    <el-drawer
			:title=" ticketDetail && ticketDetail.id ? '编辑施工方案':'创建施工方案'"
			:visible.sync="showEdit"
      :destroy-on-close="true"
      :wrapperClosable="false"
			size="80%"
			:direction="'rtl'">
      <edit :ticketDetail="ticketDetail" @closeEdit="closeEdit"></edit>
    </el-drawer>
    <!-- 施工票详情 -->
    <el-drawer
			title="施工票详情"
			:visible.sync="showDetail"
      :destroy-on-close="true"
			size="80%"
			:direction="'rtl'">
      <detail :detailId="detailId"></detail>
    </el-drawer>
    <!-- 勘察记录详情 -->
    <el-drawer
			title="勘察记录详情"
			:visible.sync="showSurveyDetail"
      :destroy-on-close="true"
			size="70%"
			:direction="'rtl'">
      <record-detail :detailId="surveyId" :showEdit="false"></record-detail>
    </el-drawer>
    <!-- 新建或修改施工方案 -->
    <el-dialog :title="ticketDetail && ticketDetail.id ? '编辑施工方案' : '新建施工方案'" :visible.sync="showSelect" :close-on-click-modal="false" width="600px">
      <select-survey v-if="showSelect" :surveyId="ticketDetail.surveyId" @confirmSurvey="confirmSurvey"></select-survey>
    </el-dialog>
  </div>
</template>

<script>
import RecordDetail from '../survey/recordDetail.vue'
import Edit from './editScheme.vue';
import Detail from './detail.vue'
import SelectSurvey from './selectSurvey.vue'
import { getSchemePage, schemeAudit, exportScheme, schemeDetails } from '@/api/scheme/index'
import { getDic } from '@/api/utils/index'
import { parseTime } from '@/utils/index.js'

const equipments = [
  {
    code: 'native',
    name: '放线滑车',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '对讲机',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '卡线器',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '棘轮紧线器',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '脚扣',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '安全带',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '传递绳',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '个人工具',
    number: '',
    specification: '',
    remark: ''
  },
  {
    code: 'native',
    name: '吊机',
    number: '',
    specification: '',
    remark: ''
  }
]
export default {
  name: 'ticketList',
  components: {
    Edit,
    Detail,
    RecordDetail,
    SelectSurvey
  },
  props:{
    type:{
      type: String
    }
  },
  data() {
    return {
      elLoading: false,
      checkedList: [],
      detailId: null,
      schemeAuditStatus: [],
      showEdit: false, //展示创建编辑页面
      showDetail: false, //展示详情页面
      showSelect: false,
      showSurveyDetail: false,
      loading: false,
      ticketDetail: {},
      selectInfo: {
        name: '',
        number: '',
        surveyNumber: '',
        location: '',
        date: [],
        auditStatus: null
      },
      surveyId: null,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
    }
  },
  mounted() {
    this.getDicsList()
    this.handleChangePage()
  },
  methods: {
    //选择导出项目
    handleSelectionChange(val) {
      this.checkedList = val
    },
    exportList() {
      let ids = this.checkedList.map(item => { return item.id })
      let params = {ids: ids, pageNum: this.page, pageSize: this.pageSize}
      this.openLoading()
      exportScheme(params).then(res => {
        let blob = res
        let reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = '施工方案'
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        this.closeLoading()
      }).catch(error => {
        this.closeLoading()
      })
    },

    getDicsList() {
      getDic('schemeAuditStatus').then(res=>{
        const { data } = res
        for (let i in data) {
          this.schemeAuditStatus.push({
            value: parseInt(i),
            label: data[i]
          }); 
        }
        // if(this.type != 'list') this.schemeAuditStatus.shift();
      })
    },
    confirmSurvey(item) {
      this.showSelect = false
      if(item) {
        this.toEdit(item)
      }
    },
    reset() {
      this.selectInfo = {
        name: '',
        number: '',
        surveyNumber: '',
        location: '',
        date: [],
        auditStatus: null
      }
    },
    close(refresh) {
      this.showDetail=false
      if(refresh) this.handleChangePage()
    },
    handleChangePage() {
      this.loading = true
      let params = {...this.selectInfo, pageNum: this.pageNum, pageSize: this.pageSize}
      if(params.date && params.date.length > 0) {
        params.startDate = params.date[0]
        params.endDate = params.date[1]
      }
      getSchemePage(params).then(res => {
        const { data } = res
        this.total = data.total
        this.tableData = data.list
        this.loading = false
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    // 审核 type 1通过 2驳回
		process(row, type) {
      schemeAudit({
        schemeId: row.id,
        toStatus: type
      }).then(() => {
        this.$message({
          type: 'success',
          message: '审核成功'
        })
        this.handleChangePage()
      })
		},
    //去创建/编辑页面
    async toEdit(item) {
      if(this.ticketDetail.id) {
        let row = await this.getDetail(this.ticketDetail.id)
        let info = {
          id: row.id,
          number: row.number,
          // checkDate: [row.startDate, row.endDate],
          jobWay: row.jobWay,
          workEnv: row.workEnv,
          drawings: row.drawings ? JSON.parse(row.drawings) : [],
          workload: row.workload,
          projectLeader: row.projectLeader,
          constructionLeader: parseInt(row.constructionLeader),
          technicalLeader: parseInt(row.technicalLeader),
          qualityLeader: parseInt(row.qualityLeader),
          materialLeader: parseInt(row.materialLeader),
          workUsers: row.workUsers ? JSON.parse(row.workUsers) : [],
          otherUsers: row.otherUsers,
          workDivision: row.workDivision,
          workTasks: row.workTasks,
          instrument: row.instrument,
          equipments: row.equipments,
          schedulingNodes: this.getSNodes(row.schedulingNodes),
          workManage: row.workManage,
          technicalManage: row.technicalManage,
          qualityControl: row.qualityControl,
          safetyControl: row.safetyControl,
          dangerPoints: row.dangerPoints,
          protectiveEquipmentDoc: row.protectiveEquipmentDoc ? JSON.parse(row.protectiveEquipmentDoc) : [],
          mechanicalIoDoc: row.mechanicalIoDoc ? JSON.parse(row.mechanicalIoDoc) : [],
          safetyToolDoc: row.safetyToolDoc ? JSON.parse(row.safetyToolDoc) : [],
          auditStatus: row.auditStatus
        }
        delete item.dangerPoints;
        this.ticketDetail = {...info, ...item}
      } else if(item.isCopy) {
        let sDetail = await this.getDetail(item.copyId)
        let schemeDetail = {
          id: null,
          workload: sDetail.workload,
          jobWay: sDetail.jobWay,
          workEnv: sDetail.workEnv,
          drawings: sDetail.drawings ? JSON.parse(sDetail.drawings) : [],
          projectLeader: sDetail.projectLeader,
          constructionLeader: parseInt(sDetail.constructionLeader),
          technicalLeader: parseInt(sDetail.technicalLeader),
          qualityLeader: parseInt(sDetail.qualityLeader),
          materialLeader: parseInt(sDetail.materialLeader),
          workUsers: sDetail.workUsers ? JSON.parse(sDetail.workUsers) : [],
          otherUsers: sDetail.otherUsers,
          workDivision: sDetail.workDivision,
          workTasks: sDetail.workTasks,
          instrument: sDetail.instrument,
          equipments: sDetail.equipments,
          schedulingNodes: this.getSNodes(sDetail.schedulingNodes),
          workManage: sDetail.workManage,
          technicalManage: sDetail.technicalManage,
          qualityControl: sDetail.qualityControl,
          safetyControl: sDetail.safetyControl,
          dangerPoints: sDetail.dangerPoints,
          protectiveEquipmentDoc: sDetail.protectiveEquipmentDoc ? JSON.parse(sDetail.protectiveEquipmentDoc) : [],
          mechanicalIoDoc: sDetail.mechanicalIoDoc ? JSON.parse(sDetail.mechanicalIoDoc) : [],
          safetyToolDoc: sDetail.safetyToolDoc ? JSON.parse(sDetail.safetyToolDoc) : [],
          auditStatus: 0 //状态
        }
        delete item.dangerPoints;
        this.ticketDetail = {...item, ...schemeDetail}
      } else {
        let info = {
          id: null,
          number: '',
          checkDate: [],
          jobWay: null,
          workEnv: '',
          drawings: [],
          workload: '',
          projectLeader: '',
          constructionLeader: null,
          technicalLeader: null,
          qualityLeader: null,
          materialLeader: null,
          workUsers: [],
          otherUsers: '',
          workDivision: '',
          workTasks: '',
          instrument: '安全围栏、施工警示牌、道路导向牌、锥形警示桩',
          equipments: [],
          schedulingNodes: [{
            serialNumber: '',
            content: '',
            safetyControl: '',
            division: '',
            checkDate: [],
          }],
          workManage: '针对该工程施工环境情况，做好人员着装统一、工器具检查必须在试验周期之内，做好疫情防控及登记工作，落实做好安全措施。',
          technicalManage: '放线时应有专人统一指挥、统一信号，保持通信畅通;做好安全监护，施工现场设置安全围栏。',
          qualityControl: '1) 认真熟悉和审查图纸，发现问题及时向设计单位提出;\n2) 对进场的施工机具、材料进行进场验收和抽查。保证以合格的产品用在工程上。\n3)检查施工机具和施工.工艺是否能按质量标准完成任务。\n4) 施工完成后进行三级验收工作，包括施工班组自验收及项目部验收环节',
          safetyControl: '1) 严格执行现场查勘制度; \n2)严格执行工作票制度; \n3)严格执行工作许可制度; \n4)严格执行工作监护制度 \n5)严格执行工作间断制度; \n6) 严格执行工作终结和恢复送电制度。',
          dangerPoints: [],
          protectiveEquipmentDoc: [],
          mechanicalIoDoc: [],
          safetyToolDoc: [],
          auditStatus: 0 //状态
        }
        this.ticketDetail = {...info, ...item}
      }
      this.showEdit = true
    },
    getSNodes(nodeList) {
      let sNodes = []
      if(nodeList && nodeList.length > 0) {
        nodeList.forEach(item => {
          sNodes.push({
            id: item.id,
            serialNumber: item.serialNumber,
            content: item.content,
            safetyControl: item.safetyControl,
            division: item.division,
            checkDate: [item.startTime, item.endTime],
          })
        })
      }
      return sNodes
    },
    async getDetail(id) {
      return schemeDetails({ id: id }).then(res => {
        return res.data
      })
    },
    closeEdit() {
      this.showEdit = false
      this.handleChangePage()
    },
    dateFormat(date) {
      if(date) {
        return parseTime(date,'{y}-{m}-{d}')
      } else {
        return '-'
      }
    },
    openLoading(){
      this.elLoading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    closeLoading(){
      this.elLoading.close();
    },
  }
}
</script>

<style lang="scss" scoped>
.select_box {
  .title {
    font-size: 14px;
    margin-bottom: 10px;
  }
}
.table_box {
  .footer {
    margin-top: 10px;
    text-align: center;
  }
}
</style>
